package com.loadmore.common.base;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

public abstract class BaseAdapter extends RecyclerView.Adapter<RVBaseHolder> {

    protected List list;
    protected Context context;
    public abstract int getLayoutId();
    public BaseAdapter(Context context) {
        this.context = context;
        list = new ArrayList();
    }
    @NonNull
    @Override
    public RVBaseHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemview = LayoutInflater.from(context).inflate(getLayoutId(), parent,false);
        return new RVBaseHolder(itemview);
    }

    @Override
    public void onBindViewHolder(@NonNull RVBaseHolder holder, final int position) {
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (clickListener != null) {
                    clickListener.click(position);
                }
            }
        });

        holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if (clickListener != null) {
                    clickListener.longClick(position);
                }
                return true;
            }
        });
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    public void appendItem(Object object) {
        list.add(object);
        notifyItemInserted(list.size());
    }

    public void removeItem(int position) {
        list.remove(position);
        notifyItemRemoved(position);
    }
    public void append(List list) {
        if (list == null)
            return;
        int start = this.list.size();
        this.list.addAll(list);
        notifyItemRangeChanged(start,list.size());
    }
    public void appendSilence(List list) {
        if (list == null)
            return;
        this.list.addAll(list);
        notifyDataSetChanged();
    }

    public void clear() {
        int count = list.size();
        this.list.clear();
        notifyItemRangeRemoved(0,count);
    }
    public void clearSilence() {
        this.list.clear();
        notifyDataSetChanged();
    }

    public Object getItem(int index) {
        return list.get(index);
    }

    private BaseClickListener clickListener;

    public void setClickListener(BaseClickListener clickListener) {
        this.clickListener = clickListener;
    }

    public interface BaseClickListener{
        public void click(int position);
        public void longClick(int position);
    }
}
